package com.wave.wavesystem.ai.agent;

import cn.hutool.core.util.StrUtil;
import com.wave.common.exception.WaveException;
import com.wave.wavesystem.ai.agent.model.AgentState;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;

import java.util.ArrayList;
import java.util.List;

/**
 * 定义 流程 的状态管理  和执行流程
 */
@Data
@Slf4j
public abstract class BaseAgent {

    // 核心属性
    private String name;

    // 提示词
    private String systemPrompt;
    private String nextPrompt;

    // 代理状态
    private AgentState state = AgentState.IDLE;

    // 当前步骤
    private int currentStep = 0;
    private int maxStep = 10;

    private ChatClient chatClient;

    // 上下文
    private List<Message> messageList = new ArrayList<>();

    public String run(String userPrompt) {
        // 1、基础校验
        if (state != AgentState.IDLE) {
            throw new RuntimeException("cannot run agent from state" + state);
        }
        if (StrUtil.isBlank(userPrompt)) {
            throw new RuntimeException("cannot run agent with empty prompt");
        }
        // 添加 消息到上下文中
        messageList.add(new UserMessage(userPrompt));
        // 定义结果列表
        List<String> results = new ArrayList<>();
        try {
            for (int i = 0; i < maxStep
                    && state != AgentState.FINISHED
                    && state != AgentState.ERROR
                    ; i++) {
                int stepNumber = i + 1;
                currentStep = stepNumber;
                log.info("Executing step:{}/{} ", stepNumber, maxStep);
                String stepResult = step();

                String result = "Step " + stepNumber + ":" + stepResult;

                results.add(result);
            }
            if (currentStep >= maxStep) {
                state = AgentState.FINISHED;
                results.add("Terminated：reached max steps （" + maxStep + "）");
            }
            return String.join("\n", results);
        } catch (Exception e) {
            state = AgentState.ERROR;
            log.error("error executing  agent", e);
            return "执行错误" + e.getMessage();
        } finally {
            clearUp();
        }

    }

    public abstract String step();

    /**
     * 清理资源
     */
    protected void clearUp() {

    }

}
